package org.jsets.fastboot.oss.service.impl;

import java.util.Date;
import java.util.List;
import org.jsets.fastboot.oss.config.ObjectStorageProperties;
import org.jsets.fastboot.oss.mapper.OutsideMapper;
import org.jsets.fastboot.oss.model.entity.Outside;
import org.jsets.fastboot.oss.model.event.OutsideDisabledEvent;
import org.jsets.fastboot.oss.service.IOutsideService;
import org.jsets.fastboot.util.DateUtils;
import org.jsets.fastboot.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baidu.fsg.uid.UidGenerator;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.eventbus.Subscribe;
import org.jsets.fastboot.oss.model.constant.StatusTypes;
import org.jsets.fastboot.oss.model.dto.OutsideQuery;

@Service
public class OutsideService extends ServiceImpl<OutsideMapper, Outside> implements IOutsideService {

	@Autowired
	private ObjectStorageProperties properties;
	
	@Autowired
	private UidGenerator uidGenerator;
	
	@Override
	public String insertOutside(Outside entity) {
		entity.setId(uidGenerator.getUID());
		entity.setStatus(StatusTypes.OK);
		entity.setCreateTime(new Date());
		if(entity.getPeriod()>0) {
			Date expiration = DateUtils.plusDays(entity.getCreateTime(), entity.getPeriod());
			entity.setDueTime(expiration);
		}
		
		StringBuilder path = new StringBuilder();
		String  encodedId = StringUtils.URLBase64Encode(String.valueOf(entity.getId()));
		path.append(this.properties.getOutsideHost());
		path.append(ObjectStorageProperties.OUTSIDE_URI);
		path.append(encodedId);
		entity.setPath(path.toString());
		
		this.save(entity);
		return entity.getPath();
	}

	@Override
	@Subscribe
	public void disableOutside(OutsideDisabledEvent event) {
		this.baseMapper.updateDisableStatus(event.getOutsideId());
		event = null;
	}
	
	@Override
	public Page<Outside> selectPage(OutsideQuery criteria) {
		Page<Outside> page = new Page<Outside>();
		page.setCurrent(criteria.getCurrent());
		page.setSize(criteria.getSize());
		List<Outside> list = this.baseMapper.selectPage(page, criteria);
		page.setRecords(list);
		return page;
	}
	
}

